/**
 * Created by Weizehua on 2017/1/24.
 */
import {Injectable} from "@angular/core";
import {Buffer} from "buffer";
import * as md5 from "js-md5"
window['Buffer'] = Buffer;

@Injectable()
export class Hash {
    private digestSalt = "T3bfFJBdTYWdZIwf8QQs9xYBsL1FJL/MYwNhtKwJEXVZODukJk6XQZJVunFOMbkPCKgRwjsvG9ZJHavcK1dXTm8qjuHkQKPG1euTyDIJcjXkO1pPOZ9ay5KTwpclN+QNk18BR0MFRL3MmR1pkl/5+U7snISvX9yJDk4d15ApBTc=";

    static async hash(data: ArrayBuffer|string, algorithm: string): Promise<Buffer> {
        if(algorithm.toLowerCase() === 'md5')
            return Buffer.from(md5.arrayBuffer(data));
        return Buffer(await crypto.subtle.digest(algorithm, await Buffer.from(data)));
    }

    async digestCaptcha(captcha: string, phone: string, expiredDate:Date): Promise<string> {
        return this.digest(captcha + phone + String(Number(expiredDate)));
    }

    async captchaTest(captcha: string, phone:string, expiredDate: Date, digest:string): Promise<boolean> {
        return digest === await this.digestCaptcha(captcha, phone, expiredDate);
    }

    async digest(data:string):Promise<string> {
        return (await Hash.hash(data + this.digestSalt, 'SHA-256')).toString('base64');
    }

    // async test(data: string, digest:string):Promise<boolean> {
    //     return digest === await this.digest(data);
    // }
}
